/*
*  Copyright 2019-2020 Zheng Jie
*
*  Licensed under the Apache License, Version 2.0 (the "License");
*  you may not use this file except in compliance with the License.
*  You may obtain a copy of the License at
*
*  http://www.apache.org/licenses/LICENSE-2.0
*
*  Unless required by applicable law or agreed to in writing, software
*  distributed under the License is distributed on an "AS IS" BASIS,
*  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*  See the License for the specific language governing permissions and
*  limitations under the License.
*/
package me.zhengjie.modules.app.hotel.service.impl;

import me.zhengjie.modules.app.hotel.domain.HotelFixedAssets;
import me.zhengjie.utils.ValidationUtil;
import me.zhengjie.utils.FileUtil;
import lombok.RequiredArgsConstructor;
import me.zhengjie.modules.app.hotel.repository.HotelFixedAssetsRepository;
import me.zhengjie.modules.app.hotel.service.HotelFixedAssetsService;
import me.zhengjie.modules.app.hotel.service.dto.HotelFixedAssetsDto;
import me.zhengjie.modules.app.hotel.service.dto.HotelFixedAssetsQueryCriteria;
import me.zhengjie.modules.app.hotel.service.dto.HotelInfoDto;
import me.zhengjie.modules.app.hotel.service.mapstruct.HotelFixedAssetsMapper;
import me.zhengjie.modules.system.domain.User;
import me.zhengjie.modules.system.service.UserService;
import me.zhengjie.modules.system.service.dto.UserDto;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import cn.hutool.core.util.IdUtil;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import me.zhengjie.utils.PageUtil;
import me.zhengjie.utils.QueryHelp;
import me.zhengjie.utils.SecurityUtils;

import java.util.List;
import java.util.Map;
import java.io.IOException;
import java.text.DecimalFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.LinkedHashMap;

/**
* @website https://el-admin.vip
* @description 服务实现
* @author Haojie Li
* @date 2021-03-28
**/
@Service
@RequiredArgsConstructor
public class HotelFixedAssetsServiceImpl implements HotelFixedAssetsService {

    private final HotelFixedAssetsRepository hotelFixedAssetsRepository;
    private final HotelFixedAssetsMapper hotelFixedAssetsMapper;
    private final UserService userService;
    
    @Override
    public Map<String,Object> queryAll(HotelFixedAssetsQueryCriteria criteria, Pageable pageable){

        if (null == criteria.getHotelId()){
            long userId = SecurityUtils.getCurrentUserId();
            UserDto user = userService.findById(userId);
            List<HotelInfoDto> list = new ArrayList<>(user.getHotels());
            if(list.size() > 0) {
                criteria.setHotelId(list.get(0).getId());
            }
        }

    	Page<HotelFixedAssets> page = hotelFixedAssetsRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder),pageable);
        return PageUtil.toPage(page.map(hotelFixedAssetsMapper::toDto));
    }

    @Override
    public List<HotelFixedAssetsDto> queryAll(HotelFixedAssetsQueryCriteria criteria){
    	long userId = SecurityUtils.getCurrentUserId();
    	UserDto user = userService.findById(userId);
		List<HotelInfoDto> list = new ArrayList<>(user.getHotels());
    	if(list.size() > 0) {
    		criteria.setHotelId(list.get(0).getId());
    	}
    	
        return hotelFixedAssetsMapper.toDto(hotelFixedAssetsRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder)));
    }

    @Override
    @Transactional
    public HotelFixedAssetsDto findById(String id) {
        HotelFixedAssets hotelFixedAssets = hotelFixedAssetsRepository.findById(id).orElseGet(HotelFixedAssets::new);
        ValidationUtil.isNull(hotelFixedAssets.getId(),"HotelFixedAssets","id",id);
        return hotelFixedAssetsMapper.toDto(hotelFixedAssets);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public HotelFixedAssetsDto create(HotelFixedAssets resources) {
    	//生成资产号
    	
    	int length = (int) hotelFixedAssetsRepository.count();
    	length = length + 1;
//    	resources.setNo(genNo(length));
    	
    	resources.setId(IdUtil.simpleUUID()); 
    	resources.setCreateUser(SecurityUtils.getCurrentUserId() + "");
    	resources.setCreateTime(LocalDateTime.now());
    	long userId = SecurityUtils.getCurrentUserId();
    	UserDto user = userService.findById(userId);
		List<HotelInfoDto> list = new ArrayList<>(user.getHotels());
    	if(list.size() > 0) {
    		resources.setHotelId(list.get(0).getId());
    		resources.setHotelName(list.get(0).getHotelName());
    	}
    	
        return hotelFixedAssetsMapper.toDto(hotelFixedAssetsRepository.save(resources));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(HotelFixedAssets resources) {
        HotelFixedAssets hotelFixedAssets = hotelFixedAssetsRepository.findById(resources.getId()).orElseGet(HotelFixedAssets::new);
        ValidationUtil.isNull( hotelFixedAssets.getId(),"HotelFixedAssets","id",resources.getId());
        hotelFixedAssets.copy(resources);
        hotelFixedAssetsRepository.save(hotelFixedAssets);
    }

    @Override
    public void deleteAll(String[] ids) {
        for (String id : ids) {
            hotelFixedAssetsRepository.deleteById(id);
        }
    }

    @Override
    public void download(List<HotelFixedAssetsDto> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (HotelFixedAssetsDto hotelFixedAssets : all) {
            Map<String,Object> map = new LinkedHashMap<>();
            map.put("资产号", hotelFixedAssets.getNo());
            map.put("资产名称", hotelFixedAssets.getName());
            map.put("资产型号", hotelFixedAssets.getModelNo());
            map.put("资产数量", hotelFixedAssets.getNum());
            map.put("备注", hotelFixedAssets.getNote());
            map.put("logo", hotelFixedAssets.getLogo());
            map.put("所属酒店ID", hotelFixedAssets.getHotelId());
            map.put("所属酒店名称", hotelFixedAssets.getHotelName());
            map.put("创建人", hotelFixedAssets.getCreateUser());
            map.put("更新人", hotelFixedAssets.getUpdateUser());
            map.put("创建时间", hotelFixedAssets.getCreateTime());
            map.put("更新时间", hotelFixedAssets.getUpdateTime());
            map.put("数据状态", hotelFixedAssets.getIsEnable());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }

    @Override
    public boolean isExistByModelNo(String hotelId, String modelNo) {
        HotelFixedAssets hotelFixedAssets = hotelFixedAssetsRepository.findByHotelIdAndModelNo(hotelId, modelNo);
        return hotelFixedAssets == null ? false : true;
    }

    public String genNo(int length) {
    	DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyMMdd");
    	
    	DecimalFormat numFormat = new DecimalFormat("000");
    	String no = numFormat.format(length);
    	String startNo = LocalDate.now().format(dtf);
    	startNo = "ZC" + startNo + no;
    	
    	//判定是否存在
    	HotelFixedAssetsQueryCriteria criteria = new HotelFixedAssetsQueryCriteria();
    	criteria.setNo(startNo);
    	List<HotelFixedAssetsDto> tempList = queryAll(criteria);
    	if(tempList != null && tempList.size() > 0) {
    		length += 1;
    		return genNo(length);
    	}
    	return startNo;
    }
}